"""
检查RBAC权限系统状态
运行方式：python -m tool.check_rbac_status
"""
import asyncio
from models.m import User, Role, UserRoleRelation, Permission, RolePermissionRelation


async def check_rbac_status():
    """检查RBAC系统状态"""
    
    print("=" * 60)
    print("RBAC权限管理系统状态检查")
    print("=" * 60)
    
    # 1. 检查角色
    print("\n1. 检查角色...")
    roles = await Role.all()
    for role in roles:
        print(f"  - {role.name} ({role.code}) - ID: {role.id}, 启用: {role.is_active}")
    
    # 2. 检查权限
    print("\n2. 检查权限...")
    permissions = await Permission.all()
    print(f"  总权限数: {len(permissions)}")
    for perm in permissions[:5]:  # 只显示前5个
        print(f"  - {perm.name} ({perm.code})")
    if len(permissions) > 5:
        print(f"  ... 还有 {len(permissions) - 5} 个权限")
    
    # 3. 检查角色权限关联
    print("\n3. 检查角色权限关联...")
    role_perms = await RolePermissionRelation.all().prefetch_related('role', 'permission')
    role_perm_map = {}
    for rp in role_perms:
        role_code = rp.role.code
        if role_code not in role_perm_map:
            role_perm_map[role_code] = []
        role_perm_map[role_code].append(rp.permission.code)
    
    for role_code, perms in role_perm_map.items():
        print(f"  {role_code} 角色拥有 {len(perms)} 个权限:")
        for perm in perms[:8]:  # 只显示前8个
            print(f"    - {perm}")
        if len(perms) > 8:
            print(f"    ... 还有 {len(perms) - 8} 个权限")
    
    # 4. 检查用户角色关联
    print("\n4. 检查用户角色关联...")
    user_roles = await UserRoleRelation.all().prefetch_related('user', 'role')
    if not user_roles:
        print("  [警告] 没有找到任何用户角色关联！")
        print("\n  检查用户数据...")
        all_users_list = await User.all()
        users = all_users_list[:10]  # 只检查前10个用户
        print(f"  总用户数: {len(all_users_list)}")
        for user in users:
            print(f"    用户ID: {user.id}, 手机号: {user.phone}, 角色(旧字段): {user.role}")
    else:
        print(f"  总关联数: {len(user_roles)}")
        user_role_map = {}
        for ur in user_roles:
            user_id = ur.user.id
            if user_id not in user_role_map:
                user_role_map[user_id] = {
                    'phone': ur.user.phone,
                    'nickname': ur.user.nickname,
                    'old_role': int(ur.user.role),
                    'rbac_roles': []
                }
            user_role_map[user_id]['rbac_roles'].append(ur.role.code)
        
        print(f"\n  已关联的用户数: {len(user_role_map)}")
        for user_id, info in list(user_role_map.items())[:10]:  # 只显示前10个
            print(f"  用户ID: {user_id}, 手机号: {info['phone']}")
            print(f"    旧角色字段: {info['old_role']} (1=USER, 2=AUTHOR, 3=ADMIN)")
            print(f"    RBAC角色: {', '.join(info['rbac_roles'])}")
    
    # 5. 检查是否存在未关联的用户
    print("\n5. 检查未关联的用户...")
    all_users = await User.all()
    all_user_ids = {user.id for user in all_users}
    linked_user_ids = {ur.user.id for ur in user_roles} if user_roles else set()
    unlinked_user_ids = all_user_ids - linked_user_ids
    
    if unlinked_user_ids:
        print(f"  [警告] 发现 {len(unlinked_user_ids)} 个用户未分配RBAC角色:")
        unlinked_users = await User.filter(id__in=list(unlinked_user_ids)[:10]).all()
        for user in unlinked_users:
            print(f"    用户ID: {user.id}, 手机号: {user.phone}, 旧角色字段: {user.role}")
        print(f"\n  建议运行: python -m tool.init_rbac_data 来为未关联用户分配角色")
    else:
        print("  [OK] 所有用户都已分配RBAC角色")
    
    print("\n" + "=" * 60)
    print("检查完成！")
    print("=" * 60)


async def main():
    """主函数"""
    from tortoise import Tortoise
    from tool.sessing import TORTOISE_ORM
    
    # 初始化数据库连接
    await Tortoise.init(config=TORTOISE_ORM)
    
    try:
        await check_rbac_status()
    finally:
        await Tortoise.close_connections()


if __name__ == "__main__":
    asyncio.run(main())
